﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MyPhotoIndex.ImageCache
{
    public class ImageCacheStream : Stream
    {
        private bool m_canRead = true;
        private Stream m_stream;
        private long m_position;
        private long m_length;

        public ImageCacheStream(string fileName, long position, long length)
        {
            m_position = position;
            m_length = length;
            m_stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            if (m_stream == null)
            {
                m_canRead = false;
                return;
            }

            m_stream.Position = position;
        }

        public ImageCacheStream(Stream stream, long position, long length)
        {
            m_position = position;
            m_length = length;
            m_stream = stream;
            if (m_stream == null)
            {
                m_canRead = false;
                return;
            }

            m_stream.Position = position;
        }

        protected override void Dispose(bool disposing)
        {
            if (m_stream != null)
            {
                m_stream.Dispose();
            }

            base.Dispose(disposing);
        }

        public override bool CanRead
        {
            get { return m_canRead; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override void Flush()
        {
            m_stream.Flush();
        }

        public override long Length
        {
            get { return m_length; }
        }

        public override long Position
        {
            get
            {
                return m_stream.Position - m_position;
            }
            set
            {
                m_stream.Position = m_position + value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return m_stream.Read(buffer, offset, Math.Min(count, (int)(Length - Position)));
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return Position += offset;
        }

        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }
    }
}
